package com.example.archive.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.archive.entity.PhysicalArchiveRetrievalRequest;
import com.example.archive.entity.User;
import com.example.archive.service.PhysicalArchiveRetrievalRequestService;
import com.example.archive.service.UserService;
import com.example.archive.util.PageParam;
import com.example.archive.util.Result;
import com.example.archive.util.UserContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/physical-archive-retrieval")
public class PhysicalArchiveRetrievalRequestController {

    private static final Logger logger = LoggerFactory.getLogger(PhysicalArchiveRetrievalRequestController.class);

    @Autowired
    private PhysicalArchiveRetrievalRequestService requestService;

    @Autowired
    private UserService userService;

    /**
     * 提交纸质档案调取申请
     */
    @PostMapping("/submit")
    public Result<String> submitRequest(@RequestBody PhysicalArchiveRetrievalRequest request) {
        try {
            Integer userId = UserContext.getUserId();
            if (userId == null) {
                return Result.fail(401, "用户未登录");
            }
            
            request.setUserId(userId);
            logger.info("用户 {} 提交纸质档案调取申请，档案ID: {}", userId, request.getArchiveId());
            
            return requestService.submitRequest(request);
        } catch (Exception e) {
            logger.error("提交纸质档案调取申请失败", e);
            return Result.fail(500, "提交申请失败");
        }
    }

    /**
     * 分页查询申请列表
     */
    @GetMapping("/list")
    public Result<IPage<PhysicalArchiveRetrievalRequest>> listRequests(PageParam pageParam, 
                                                                      @RequestParam(required = false) String status) {
        try {
            Integer userId = UserContext.getUserId();
            if (userId == null) {
                return Result.fail(401, "用户未登录");
            }
            
            // 获取用户角色
            Result<User> userResult = userService.getUserById(userId);
            if (userResult.getCode() != 200 || userResult.getData() == null) {
                return Result.fail(401, "无法获取用户信息");
            }
            String userRole = userResult.getData().getRole();
            
            logger.info("查询纸质档案调取申请列表，用户ID: {}, 角色: {}", userId, userRole);
            
            return requestService.listRequests(pageParam, userId, userRole, status);
        } catch (Exception e) {
            logger.error("查询申请列表失败", e);
            return Result.fail(500, "查询失败");
        }
    }

    /**
     * 审批申请
     */
    @PutMapping("/approve/{id}")
    public Result<String> approveRequest(@PathVariable Integer id, 
                                       @RequestParam String status, 
                                       @RequestParam(required = false) String notes) {
        try {
            Integer approverId = UserContext.getUserId();
            if (approverId == null) {
                return Result.fail(401, "用户未登录");
            }
            
            // 获取用户角色
            Result<User> userResult = userService.getUserById(approverId);
            if (userResult.getCode() != 200 || userResult.getData() == null) {
                return Result.fail(401, "无法获取用户信息");
            }
            String userRole = userResult.getData().getRole();
            
            if (!"企业领导".equals(userRole)) {
                return Result.fail(403, "无权限进行审批");
            }
            
            logger.info("用户 {} 审批纸质档案调取申请，申请ID: {}, 状态: {}", approverId, id, status);
            
            return requestService.approveRequest(id, status, notes, approverId);
        } catch (Exception e) {
            logger.error("审批申请失败", e);
            return Result.fail(500, "审批失败");
        }
    }

    /**
     * 获取申请详情
     */
    @GetMapping("/{id}")
    public Result<PhysicalArchiveRetrievalRequest> getRequestDetail(@PathVariable Integer id) {
        try {
            Integer userId = UserContext.getUserId();
            if (userId == null) {
                return Result.fail(401, "用户未登录");
            }
            
            logger.info("获取纸质档案调取申请详情，申请ID: {}", id);
            return requestService.getRequestDetail(id);
        } catch (Exception e) {
            logger.error("获取申请详情失败", e);
            return Result.fail(500, "获取详情失败");
        }
    }

    /**
     * 确认档案调取
     */
    @PutMapping("/confirm-retrieval/{id}")
    public Result<String> confirmRetrieval(@PathVariable Integer id) {
        try {
            Integer userId = UserContext.getUserId();
            if (userId == null) {
                return Result.fail(401, "用户未登录");
            }
            
            logger.info("确认纸质档案调取，申请ID: {}", id);
            return requestService.confirmRetrieval(id);
        } catch (Exception e) {
            logger.error("确认档案调取失败", e);
            return Result.fail(500, "确认失败");
        }
    }

    /**
     * 确认档案归还
     */
    @PutMapping("/confirm-return/{id}")
    public Result<String> confirmReturn(@PathVariable Integer id) {
        try {
            Integer userId = UserContext.getUserId();
            if (userId == null) {
                return Result.fail(401, "用户未登录");
            }
            
            logger.info("确认纸质档案归还，申请ID: {}", id);
            return requestService.confirmReturn(id);
        } catch (Exception e) {
            logger.error("确认档案归还失败", e);
            return Result.fail(500, "确认失败");
        }
    }
} 